<?php

namespace app\common\model\Post;

use think\Model;
use traits\model\SoftDelete;

class Post extends Model
{
    use SoftDelete;

    protected $name = "post";

    protected $autoWriteTimestamp = true;

    protected $createTime = 'createtime';
    protected $updateTime = false;
    // 软删除字段
    protected $deleteTime = 'deletetime';

    public function business()
    {
        return $this->belongsTo('app\common\model\Business\Business', 'busid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function cate()
    {
        return $this->belongsTo('app\common\model\Post\Cate', 'cateid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    protected $append = [
        'create_time_text',
        'common_count',
        'collect_count',
    ];

    // 创建时间
    public function getCreatetimeTextAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : '';

        if (empty($createtime)) {
            return '';
        }

        return date('Y-m-d', $createtime);
    }

    // 评论人数
    public function getCommonCountAttr($value, $data)
    {
        $postid = $data['id'];

        $count = model('post.Comment')->where(['postid' => $postid])->group('busid')->count();

        return $count ? $count : 0;
    }

    // 关注问题人数
    public function getCollectCountAttr($value, $data)
    {
        $postid = $data['id'];

        $count = model('post.Collect')->where(['postid' => $postid])->count();

        return $count ? $count : 0;
    }

}
